package com.sxu.forkjoindemo;

import java.util.concurrent.RecursiveTask;

public class MyTask2 extends RecursiveTask<Integer> {
    private int start;
    private int end;
    public MyTask2(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public String toString() {
        return "MyTask2 [start=" + start + ", end=" + end + "]";
    }

    @Override
    protected Integer compute() {
        if(start == end){
            System.out.println(Thread.currentThread().getName() + ": join():" + start);
            return start;
        }
        if(end - start == 1){
            System.out.println(Thread.currentThread().getName() + ": join():" + start + " + " + end + " = " + (start+end));
            return start + end;
        }
        int middle = (start + end)/2;

        MyTask2 t1 = new MyTask2(start, middle);
        t1.fork();
        MyTask2 t2 = new MyTask2(middle+1, end);
        t2.fork();

        int result = t1.join() + t2.join();
        System.out.println(Thread.currentThread().getName() + ": join():" + t1 + " + " + t2 + " = " + result);
        return result;
    }
}
